package org.lanyu.springainovel.chat.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.lanyu.springainovel.chat.service.KnowledgeDocumentService;
import org.lanyu.springainovel.chat.entity.KnowledgeBase;
import org.lanyu.springainovel.common.entity.User;
import org.lanyu.springainovel.chat.service.KnowledgeBaseService;
import org.lanyu.springainovel.common.service.UserService;
import org.lanyu.springainovel.common.vo.RestVO;
import org.lanyu.springainovel.chat.entity.KnowledgeDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文档管理控制�? */
@Tag(name = "文档管理", description = "文档的增删改查接")
@RestController
@RequestMapping("/document")
public class KnowledgeDocumentController {

    @Autowired
    private KnowledgeDocumentService documentService;

    @Autowired
    private KnowledgeBaseService knowledgeBaseService;

    @Autowired
    private UserService userService;

    /**
     * 添加文档（文本内容）
     */
    @Operation(summary = "添加文档（文本内容）")
    @PostMapping("/add")
    public RestVO<KnowledgeDocument> addDocument(@RequestBody KnowledgeDocument document) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return RestVO.fail("用户未登录");
            }
            User user = userService.getUserByUsername(authentication.getName());
            
            // 验证知识�?
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(document.getKnowledgeBaseId());
            if (knowledgeBase == null) {
                return RestVO.fail("知识库不存在");
            }

            // 设置创建�?
            document.setCreatedBy(user.getId());
            
            // 对于文本添加的文档，如果没有设置fileSize，设置为0
            if (document.getFileSize() == null) {
                document.setFileSize(0L);
            }
            
            KnowledgeDocument savedDocument = documentService.saveDocument(document);

            return RestVO.success(savedDocument);
        } catch (Exception e) {
            return RestVO.fail("添加文档失败: " + e.getMessage());
        }
    }

    /**
     * 根据文件信息创建文档
     */
    @Operation(summary = "根据文件信息创建文档")
    @PostMapping("/create-from-file")
    public RestVO<KnowledgeDocument> createDocumentFromFile(@RequestBody KnowledgeDocument document) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return RestVO.fail("用户未登录");
            }
            User user = userService.getUserByUsername(authentication.getName());
            
            // 验证知识�?
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(document.getKnowledgeBaseId());
            if (knowledgeBase == null) {
                return RestVO.fail("知识库不存在");
            }

            // 创建文档
            KnowledgeDocument savedDocument = documentService.createDocumentFromFile(
                document.getFileName(), 
                document.getFilePath(), 
                document.getTitle(), 
                document.getFileSize(), 
                document.getKnowledgeBaseId(), 
                user.getId());

            return RestVO.success(savedDocument);
        } catch (Exception e) {
            return RestVO.fail("创建文档失败: " + e.getMessage());
        }
    }

    /**
     * 获取知识库下的所有文�?     */
    @Operation(summary = "获取知识库下的所有文件")
    @GetMapping("/list/{knowledgeBaseId}")
    public RestVO<List<KnowledgeDocument>> getDocumentsByKnowledgeBase(@PathVariable Long knowledgeBaseId) {
        try {
            // 验证知识�?
            KnowledgeBase knowledgeBase = knowledgeBaseService.getKnowledgeBase(knowledgeBaseId);
            if (knowledgeBase == null) {
                return RestVO.fail("知识库不存在");
            }

            List<KnowledgeDocument> documents = documentService.getDocumentsByKnowledgeBaseId(knowledgeBaseId);
            return RestVO.success(documents);
        } catch (Exception e) {
            return RestVO.fail("获取文档列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取文档详情
     */
    @Operation(summary = "获取文档详情")
    @GetMapping("/{id}")
    public RestVO<KnowledgeDocument> getDocument(@PathVariable Long id) {
        try {
            // 获取文档
            KnowledgeDocument document = documentService.getDocumentById(id);
            if (document == null) {
                return RestVO.fail("文档不存在");
            }

            return RestVO.success(document);
        } catch (Exception e) {
            return RestVO.fail("获取文档详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新文档
     */
    @Operation(summary = "更新文档")
    @PutMapping("/{id}")
    public RestVO<KnowledgeDocument> updateDocument(@PathVariable Long id, @RequestBody KnowledgeDocument document) {
        try {
            // 获取现有文档
            KnowledgeDocument existingDocument = documentService.getDocumentById(id);
            if (existingDocument == null) {
                return RestVO.fail("文档不存在");
            }

            // 更新文档
            document.setId(id);
            document.setKnowledgeBaseId(existingDocument.getKnowledgeBaseId());
            document.setCreatedBy(existingDocument.getCreatedBy());

            KnowledgeDocument updatedDocument = documentService.updateDocument(document);
            return RestVO.success(updatedDocument);
        } catch (Exception e) {
            return RestVO.fail("更新文档失败: " + e.getMessage());
        }
    }

    /**
     * 删除文档
     */
    @Operation(summary = "删除文档")
    @DeleteMapping("/{id}")
    public RestVO<Map<String, String>> deleteDocument(@PathVariable Long id) {
        try {
            // 获取文档
            KnowledgeDocument document = documentService.getDocumentById(id);
            if (document == null) {
                return RestVO.fail("文档不存在");
            }

            boolean result = documentService.deleteDocument(id);

            if (result) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "文档删除成功");
                return RestVO.success(response);
            } else {
                return RestVO.fail("文档删除失败");
            }
        } catch (Exception e) {
            return RestVO.fail("删除文档失败: " + e.getMessage());
        }
    }

    /**
     * 分页获取文档列表
     */
    @Operation(summary = "分页获取文档列表")
    @GetMapping
    public RestVO<Map<String, Object>> listDocuments(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long knowledgeBaseId) {

        try {
            Page<KnowledgeDocument> result = documentService.listDocuments(page, size, knowledgeBaseId);

            Map<String, Object> response = new HashMap<>();
            response.put("total", result.getTotal());
            response.put("pages", result.getPages());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("records", result.getRecords());

            return RestVO.success(response);
        } catch (Exception e) {
            return RestVO.fail("获取文档列表失败: " + e.getMessage());
        }
    }
}
